#!/usr/bin/python

import RPi.GPIO as GPIO
import mosquitto
import time
import os
import sys

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)

if(len(sys.argv))<>3:
    print "2 Arguments required "+str(len(sys.argv))+" provided - GPIO Pin and topic"
    sys.exit(8)

pin = int(sys.argv[1])
topic = sys.argv[2]

def on_message(mosq, msg):
    if(msg.payload == "high"): GPIO.output(pin,GPIO.HIGH)
    if(msg.payload == "low"): GPIO.output(pin,GPIO.LOW)

def on_connect(mosq, rc):
    if rc==0: 
        print("Mosquitto connected ok")
        listener.subscribe(topic, 1)
    else:
        listener.connect("KitchenPI.home")

def on_disconnect(mosq):
    print("Disconnected")

def on_subscribe(mosq, mid, rc):
    print("Subscribed ok")

listener = mosquitto.Mosquitto(os.uname()[1]+"-"+str(os.getpid()))
print("Created client")
listener.on_connect = on_connect
listener.on_disconnect = on_disconnect
listener.on_message = on_message
print("Defined callbacks")

while 1==1:
    while listener.loop()==0:
        time.sleep(0.1)
    time.sleep(10)
    listener.connect("KitchenPI.home")
